package com.ghsc.ghxc.jsb.ui.live.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.dingpaas.interaction.ImCancelMuteUserReq
import com.alibaba.dingpaas.interaction.ImGetGroupStatisticsReq
import com.alibaba.dingpaas.interaction.ImGetGroupStatisticsRsp
import com.alibaba.dingpaas.interaction.ImListGroupUserReq
import com.alibaba.dingpaas.interaction.ImListGroupUserRsp
import com.alibaba.dingpaas.interaction.ImMuteUserReq
import com.alibaba.dingpaas.interaction.ImSendMessageToGroupReq
import com.alibaba.dingpaas.interaction.ImSendMessageToGroupRsp
import com.alivc.auicommon.common.base.util.Utils
import com.alivc.auicommon.common.biz.exposable.enums.LiveStatus
import com.alivc.auicommon.common.roombase.Const
import com.alivc.auicommon.core.base.Actions
import com.alivc.auicommon.core.event.EventManager
import com.alivc.auimessage.listener.InteractionCallback
import com.alivc.auimessage.model.base.AUIMessageModel
import com.alivc.auimessage.model.base.InteractionError
import com.alivc.auimessage.model.lwp.JoinGroupRequest
import com.alivc.auimessage.model.lwp.JoinGroupResponse
import com.alivc.auimessage.model.lwp.LeaveGroupRequest
import com.aliyun.aliinteraction.InteractionEngine
import com.aliyun.aliinteraction.InteractionService
import com.aliyun.aliinteraction.base.Callback
import com.aliyun.aliinteraction.base.Error
import com.aliyun.aliinteraction.enums.BroadcastType
import com.aliyun.aliinteraction.enums.SortType
import com.aliyun.aliinteraction.player.LivePlayerService
import com.aliyun.aliinteraction.player.LivePlayerServiceImpl
import com.aliyun.aliinteraction.roompaas.message.AUIMessageService
import com.aliyun.aliinteraction.roompaas.message.AUIMessageServiceFactory
import com.aliyun.aliinteraction.roompaas.message.listener.SimpleOnMessageListener
import com.aliyun.aliinteraction.roompaas.message.model.CusuLiveGoodsModel
import com.aliyun.aliinteraction.roompaas.message.model.CusuLiveGoodsRefreshModel
import com.aliyun.aliinteraction.roompaas.message.model.CusuLiveRedModel
import com.aliyun.aliinteraction.roompaas.message.model.CusuSendMsgModel
import com.aliyun.aliinteraction.roompaas.message.model.GiftModel
import com.aliyun.aliinteraction.uikit.core.ComponentManager
import com.aliyun.aliinteraction.uikit.core.LiveConst
import com.aliyun.aliinteraction.uikit.uibase.util.DialogUtil
import com.aliyun.auiappserver.AppServerApi
import com.aliyun.auiappserver.model.GetMeetingInfoRequest
import com.aliyun.auiappserver.model.LiveModel
import com.aliyun.auiappserver.model.MeetingInfo
import com.aliyun.auiappserver.model.StopLiveRequest
import com.aliyun.auipusher.AnchorPreviewHolder
import com.aliyun.auipusher.LiveContext
import com.aliyun.auipusher.LiveParam
import com.aliyun.auipusher.LiveRole
import com.aliyun.auipusher.LiveService
import com.aliyun.auipusher.LiveServiceImpl
import com.aliyun.auipusher.manager.LiveLinkMicPushManager
import com.blankj.utilcode.util.GsonUtils
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.cn.appcore.utils.TimeUtils
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityLiveBinding
import com.ghsc.ghxc.jsb.ui.integral.activity.IntegralGoodsDetailActivity
import com.ghsc.ghxc.jsb.ui.live.adapter.LiveHeadListAdapter
import com.ghsc.ghxc.jsb.ui.live.bean.AppLiveTaskData
import com.ghsc.ghxc.jsb.ui.live.bean.CustImNoticeBean
import com.ghsc.ghxc.jsb.ui.live.bean.CustLiveSendDataBean
import com.ghsc.ghxc.jsb.ui.live.bean.CustObserverLiveDataBean
import com.ghsc.ghxc.jsb.ui.live.bean.LiveExtendDataBean
import com.ghsc.ghxc.jsb.ui.live.bean.LiveMessageDataBean
import com.ghsc.ghxc.jsb.ui.live.bean.LiveSendRedResult
import com.ghsc.ghxc.jsb.ui.live.bean.LiveUserInfoBean
import com.ghsc.ghxc.jsb.ui.live.bean.SendGiftBean
import com.ghsc.ghxc.jsb.ui.live.view.CustRouter
import com.ghsc.ghxc.jsb.ui.live.view.LiveAudienceListPopupView
import com.ghsc.ghxc.jsb.ui.live.view.LiveBlackList
import com.ghsc.ghxc.jsb.ui.live.view.LiveBlackList.isTaskComment
import com.ghsc.ghxc.jsb.ui.live.view.LiveBlackList.isTaskShare
import com.ghsc.ghxc.jsb.ui.live.view.LiveCartListAudiencePopupView
import com.ghsc.ghxc.jsb.ui.live.view.LiveCartListPopupView
import com.ghsc.ghxc.jsb.ui.live.view.LiveRedPopupView
import com.ghsc.ghxc.jsb.ui.live.view.LiveSetPopupView
import com.ghsc.ghxc.jsb.ui.live.view.LiveSharePopupView
import com.ghsc.ghxc.jsb.ui.live.view.LiveTheChartsBangListPopupView
import com.ghsc.ghxc.jsb.ui.live.view.LiveUserInfoPopupView
import com.ghsc.ghxc.jsb.ui.live.view.RewardLayout
import com.ghsc.ghxc.jsb.ui.live.view.gif.GiftPopup
import com.ghsc.ghxc.jsb.ui.live.view.widget.TipsSubPopViiew
import com.ghsc.ghxc.jsb.utils.AnimUtils
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import de.hdodenhof.circleimageview.CircleImageView
import java.net.URL
import java.util.Queue
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue
import kotlin.random.Random

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.live.activity
 * 类名：LiveBroadcastActivity
 * 创建时间：2024/5/10 11:57
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 直播页面
 */
class LiveBroadcastActivity  : BaseVMActivity<LiveViewModel, ActivityLiveBinding>(){
    override fun attachLayoutRes(): Int {
        return R.layout.activity_live
    }

    override fun attachVMClass(): Class<LiveViewModel>? {
        return LiveViewModel::class.java
    }

    var bundle : Bundle? =null
    var   pageParam: LiveParam? =null

    private var role: LiveRole? = null
    private var liveStatus: LiveStatus? = null
    private var liveId: String? = null
    private var liveModel: LiveModel? = null
    private var userNick: String? = null
    private var userExtension: String? = null
    private var groupId: String? = null
    private var tips: String? = null
    private var userAvatar: String? = null


    //消息服务  弹幕  开始直播 结束直播 更新 申请连麦 等
    private var auiMessageService: AUIMessageService? = null
    //交互
    private var interactionService: InteractionService? = null

    //媒体推流服务
    private var pushManager: LiveLinkMicPushManager? = null
    //页面状态
    private var liveContext: LiveContext? = null


    //直播详情
    private var liveService: LiveService? = null
    //直播播放服务 播放 暂停 等
    private var livePlayerService: LivePlayerService? = null
    private val componentManager = ComponentManager()
    private val anchorPreviewHolder = AnchorPreviewHolder()


    private var isPushing = false
    private var isFollow=false





    private val mHeadAdapter: LiveHeadListAdapter by lazy { LiveHeadListAdapter() }
    var mListHead = arrayListOf<LiveUserInfoBean>()
    var isOnClick =false



    var checkId="" //观众当前选择的打赏id

    private  var isShop: Int =0 //是否开启购物



    private var goodsPid ="" //商品id
    private var userRid: String by Preference(HttpConstant.USER_RID, "")
    private var userId: String by Preference(HttpConstant.USER_ID, "")

    var packetid:String= ""
    var userName = UserManager.getUserName()
    val random = Random(System.currentTimeMillis())




    var myCountDownTimer: MyCountDownTimer? = null


    override fun initView() {
        binding.layoutClear.addClearViews(binding.roomBottomLayout, binding.roomMessageLayout, binding.linkMic)
        bundle=intent.extras
        pageParam = intent.getSerializableExtra(LiveConst.PARAM_KEY_LIVE_PARAM) as LiveParam?
        pageParam?.let {
            liveId = it.liveId
            liveModel =it.liveModel
            role = it.role
            liveStatus = LiveStatus.of(liveModel!!.status)
            userNick = it.userNick
            userAvatar=it.userAvatar
            userExtension = it.userExtension
            tips = pageParam!!.notice
            groupId = liveModel!!.chatId
            loge("liveModel="+liveModel)
        }
//        loge("我擦=直播间=="+liveModel!!.pushUrlInfo.rtmpUrl)
        val engine = InteractionEngine.instance()
        if (!engine.isLogin) {
            showToast("未登录")
            finish()
            return
        }
        interactionService = InteractionEngine.instance().interactionService
        pushManager = LiveLinkMicPushManager(this, null)
        liveContext = LiveContextImpl()
        val decorView = window.decorView
        componentManager.scanComponent(decorView)
        componentManager.dispatchInit(liveContext!!)
        joiGroup(liveContext!!)


        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CustSignKey.LIVE_IM_REN_COUNT && rxBusBean.sign == CustSignKey.LIVE_IM_REN_COUNT -> {
                        //人数的倍数
                        binding.liveCount.setNewCount()
                    }

                    rxBusBean.id == CustSignKey.IM_LIVE_REN_COUNT && rxBusBean.sign == CustSignKey.IM_LIVE_REN_COUNT -> {
                        //人数的倍数
                        val count = rxBusBean.anyBean as Int
                        LiveBlackList.numberMultiple =count
                        CustRouter.sendLiveRenCountMsg(liveContext!!.groupId,count.toString())
                        binding.liveCount.setNewCount()
                    }
                    rxBusBean.id == CustSignKey.LIVE_IM_SEND_MSG && rxBusBean.sign == CustSignKey.LIVE_IM_SEND_MSG -> {
                        //虚拟发送信息  接收到 没有  用到  暂时
                        val bean =rxBusBean.anyBean as CusuSendMsgModel
                        loge("发送消息队列 接收到=="+bean.msg)
//                       val bean =rxBusBean.anyBean as CusuSendMsgModel
//                        var mList = arrayListOf<MessageModel>()
//                        mList.add(MessageModel( bean.uid,bean.nickname,bean.msg))
//                        binding.roomMessageLayout.addMessageToPanel2(mList)
                    }
                    rxBusBean.id == CustSignKey.IM_LIVE_SEND_MSGS && rxBusBean.sign == CustSignKey.IM_LIVE_SEND_MSGS -> {
                        //虚拟发送信息
                        val bean = rxBusBean.anyBean as CustObserverLiveDataBean
//                        binding.liveInputView.sendCustMsg(bean)
//                        for (i in bean.data.list.indices){
//                            queueMsg.add(MessageModel(bean.data.list[i].uid,bean.data.list[i].nickname,bean.data.msg))
//                        }
                        queueMsg.addAll(bean.data.list)
                        if (queueMsg.size > 0) {
                            Thread {
                                liveSendMsg()
                            }.start()

                        }
                    }
                    rxBusBean.id == CustSignKey.CHAT_LIVE_ADD && rxBusBean.sign == CustSignKey.CHAT_LIVE_ADD -> {
                        //收到融云直播间黑名单add名单
                        var context= rxBusBean.anyBean as String
                        if(!TextUtils.isEmpty(context))
                            CustRouter.sendLiveBlackMsg(context,liveContext!!.groupId,1)

                    }
                    rxBusBean.id == CustSignKey.CHAT_LIVE_DEL && rxBusBean.sign == CustSignKey.CHAT_LIVE_DEL -> {
                        //收到融云直播间黑名单del名单
                        var context= rxBusBean.anyBean as String
                        if(!TextUtils.isEmpty(context))
                            CustRouter.sendLiveBlackMsg(context,liveContext!!.groupId,2)
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_MAI_ADD && rxBusBean.sign == CustSignKey.CUST_LIVE_MAI_ADD -> {
                        //麦上增加
                        var userId= rxBusBean.anyBean as String
                        getLianMaiListData()
//                        if (mLianMaiAdapter.data.size>0){
//                            ongetLianMaiListData(userId)
//                        }else{
//                            //连麦 list
//                            getLianMaiListData()
//                        }
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_MAI_REDUCE && rxBusBean.sign == CustSignKey.CUST_LIVE_MAI_REDUCE -> {
                        //麦上减少
                        var userId= rxBusBean.anyBean as String
                        if(userId == checkId) checkId=""
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_STOP && rxBusBean.sign == CustSignKey.CUST_LIVE_STOP -> {
                        //当直播间结束之后
                        if (role== LiveRole.ANCHOR){
                            var liveBean =rxBusBean.anyBean as LiveContext
                            var bundle = Bundle()
                            bundle.putString("liveId",liveId!!)
                            startActivityFinish(LiveEndStopActivity().javaClass,bundle)

                        }else{
                            XPopup.Builder(this)
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                                .customHostLifecycle(lifecycle)
                                .dismissOnTouchOutside(false)
                                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                                .asCustom(
                                    TipsSubPopViiew(this,"当前直播已结束",
                                        btnSub={
                                            finish()
                                        })
                                )
                                .show()
                        }

                    }
                    rxBusBean.id == CustSignKey.CHAT_LIVE_ORDER && rxBusBean.sign == CustSignKey.CHAT_LIVE_ORDER -> {
                        //收到融云直播间订单消息
                        val content = rxBusBean.anyBean as String
                        loge("收到融云直播间订单消息"+content)
                        Thread {
                            loopBarrageDatas.offer(content) //添加数据
                        }.start()
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_GIF_PW && rxBusBean.sign == CustSignKey.CUST_LIVE_GIF_PW -> {
                        //todo  礼物
                        var bean=rxBusBean.anyBean as CustImNoticeBean
                        XPopup.Builder(this@LiveBroadcastActivity)
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                            .customHostLifecycle(lifecycle)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(false)
                            .enableDrag(false)
                            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                            //这个属性必须加，不然GiftFragment出问题
                            .isViewMode(true)
                            .asCustom(
                                GiftPopup(this@LiveBroadcastActivity, bean,liveId!! ,checkId ,pageParam!!.liveModel.anchorId)
                            )
                            .show()

                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_IS_FOLLOW && rxBusBean.sign == CustSignKey.CUST_LIVE_IS_FOLLOW -> {
                        //关注
                        val map: HashMap<String, Any> = HashMap()
                        map["tuid"] = pageParam!!.liveModel.anchorId
                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onUserFollowMethod(it1) }


                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_SHARE_URL && rxBusBean.sign == CustSignKey.CUST_LIVE_SHARE_URL -> {
                        //todo  分享
                        var url=rxBusBean.anyBean as String
                        loge("分享链接11="+url)
                        var item1 =url.split("http://live.rtc.guohuamall.com/live/")
                        var item2 =item1[item1.size-1].split(".m3u8")
                        var shareUrl1 =item2[0]
                        var item3 =url.split("auth_key=")
                        var shareUrl2 =item3[item3.size-1]
//                        分享
                        val bean = GsonUtil.GsonToJsonClass(
                            liveModel!!.extend,
                            LiveExtendDataBean::class.java
                        )
                        var img =bean.cover_url.split("liveCover/")
                        var LiveShareUrl= ""
                        var confBean =UserManager.getConfig()
                        confBean?.let {
                            var sysConfigResultData = it.getSysConfigBean(CustKey.configK124 )
                            if(sysConfigResultData!=null){
                                if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                                    LiveShareUrl = sysConfigResultData.cfg_value
                                }
                            }
                        }
//                        var sharUrl =confBean!!.getLiveShareUrl()+"&uid="+UserManager.getUserId()+"&auth_key="+shareUrl2+"&stream="+shareUrl1+"&img="+ img[img.size-1].substring(0,img[img.size-1].length-4)
                        //封面。
                        val extendJson: String = liveModel!!.extend
                        val liveUserInfo = GsonUtil.GsonToJsonClass(
                            extendJson,
                            LiveExtendDataBean::class.java
                        )

                        if (!TextUtils.isEmpty(url)){
                            XPopup.Builder(this@LiveBroadcastActivity)
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .customHostLifecycle(lifecycle)
                                .dismissOnTouchOutside(true)
                                .hasShadowBg(false)
                                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                                .asCustom(
                                    LiveSharePopupView(this@LiveBroadcastActivity,"",LiveShareUrl,liveModel!!.anchorId,liveId!!,liveUserInfo,liveModel!!.title)
                                )
                                .show()
                        }

                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_MESSAGE_UP && rxBusBean.sign == CustSignKey.CUST_LIVE_MESSAGE_UP -> {
                        //是否 禁言
//                        var bean =rxBusBean.anyBean as CusuUpMsgModel
//                        var liveData: LiveAdminDataBean? = UserManager.getLiveAdminData() ?: return@subscribe
//                        if (liveData!!.liveId==bean.liveId){
//                            for (i in liveData.list.indices){
//                                if (liveData.list[i].userId==bean.userId){
//                                    isSetUpImMsg(bean.otherId, bean.isUpMsg==1)
//                                    break
//                                }
//                            }
//                        }
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_MESSAGE && rxBusBean.sign == CustSignKey.CUST_LIVE_MESSAGE -> {
                        //点击消息面板
                        var custMessageBean = rxBusBean.anyBean as LiveMessageDataBean
                        if (UserManager.getUserId()==custMessageBean.anchorId){
                            //这是主播
                            XPopup.Builder(this@LiveBroadcastActivity)
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .customHostLifecycle(lifecycle)
                                .dismissOnTouchOutside(true)
                                .hasShadowBg(false)
                                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                                .asCustom(
                                    LiveSetPopupView(
                                        this@LiveBroadcastActivity, custMessageBean,
                                        msgConfirm = {
                                            isSetUpImMsg(custMessageBean.model.userId,true)
                                        },
                                        msgCancel = {
                                            isSetUpImMsg(custMessageBean.model.userId,false)
                                        },
                                        tvBtnSee= {
                                            //查看
                                            seeInfo(custMessageBean.model.userId)
                                        }
                                    )
                                )
                                .show()
                        }else{
                            seeInfo(custMessageBean.model.userId)
                        }


                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_FUDAI_SUCCESS && rxBusBean.sign == CustSignKey.CUST_LIVE_FUDAI_SUCCESS -> {
                        //直播间发送红包成功
                        var bean = rxBusBean.anyBean as LiveSendRedResult
                        bean.let {
                            packetid=it.packet_id.toString()
                            binding.hongbao.visibility=View.VISIBLE
                            var time :Int=0
                            if (it.count_down>0){
                                time =it.count_down.toInt()
                                if (time>0){
                                    binding.tvRedTime.visibility=View.VISIBLE
                                    myCountDownTimer=null
                                    myCountDownTimer = MyCountDownTimer( (  (60 *time) *1000  ).toLong() , 1000)
                                    myCountDownTimer?.start()
                                    CustRouter.sendLiveAllMsg(liveContext!!.groupId,packetid,(60 *time),pageParam!!.liveModel.anchorId,pageParam!!.liveModel.anchorNick,"大吉大利")

                                }else{
                                    binding.tvRedTime.visibility=View.GONE
                                    CustRouter.sendLiveAllMsg(liveContext!!.groupId,packetid,0,pageParam!!.liveModel.anchorId,pageParam!!.liveModel.anchorNick,"大吉大利")
                                }
                            }else{
                                binding.tvRedTime.visibility=View.GONE
                                CustRouter.sendLiveAllMsg(liveContext!!.groupId,packetid,0,pageParam!!.liveModel.anchorId,pageParam!!.liveModel.anchorNick,"大吉大利")
                            }
                        }
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_FUDAI_PW && rxBusBean.sign == CustSignKey.CUST_LIVE_FUDAI_PW -> {
                        //  todo  发红包
                        XPopup.Builder(this@LiveBroadcastActivity)
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                            .customHostLifecycle(lifecycle)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(false)
                            .enableDrag(false)
                            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                            //这个属性必须加，不然GiftFragment出问题
                            .isViewMode(true)
                            .autoOpenSoftInput(true)
                            .dismissOnTouchOutside(true)
                            .dismissOnBackPressed(true)
                            .asCustom(
                                LiveRedPopupView(this@LiveBroadcastActivity, liveContext!!.groupId,liveModel!!.anchorId,liveId!!)
                            )
                            .show()
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_RED && rxBusBean.sign == CustSignKey.CUST_LIVE_RED -> {
                        // 观众 收到主播发红包的标识
                        var custMessageBean = rxBusBean.anyBean as CusuLiveRedModel
                        loge("当前红包id ="+packetid+"packetid==="+custMessageBean.packetid)
                        if (!TextUtils.isEmpty(custMessageBean.packetid)){
                            packetid=custMessageBean.packetid
                            binding.hongbao.visibility= View.VISIBLE
                            if (custMessageBean.time>0){
                                binding.tvRedTime.visibility= View.VISIBLE
                                myCountDownTimer=null
                                myCountDownTimer = MyCountDownTimer( (1000 *custMessageBean.time).toLong() , 1000)
                                myCountDownTimer?.start()
                            }else{
                                binding.tvRedTime.visibility= View.GONE
                            }
                        }
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_CART && rxBusBean.sign == CustSignKey.CUST_LIVE_CART -> {
                        //todo  直播间 购物
                        var isOwner= rxBusBean.anyBean as Boolean
                        if(isOwner){
                            XPopup.Builder(this@LiveBroadcastActivity)
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .customHostLifecycle(lifecycle)
                                .dismissOnTouchOutside(true)
                                .hasShadowBg(false)
                                .enableDrag(false)
                                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                                //这个属性必须加，不然GiftFragment出问题
                                .isViewMode(true)
                                .dismissOnTouchOutside(true)
                                .dismissOnBackPressed(true)
                                .asCustom(
                                    LiveCartListPopupView(this@LiveBroadcastActivity, liveContext!!.groupId,liveModel!!.anchorId,liveId!!)

                                )
                                .show()
                        }else{
                            XPopup.Builder(this@LiveBroadcastActivity)
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .customHostLifecycle(lifecycle)
                                .dismissOnTouchOutside(true)
                                .hasShadowBg(false)
                                .enableDrag(false)
                                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                                //这个属性必须加，不然GiftFragment出问题
                                .isViewMode(true)
                                .dismissOnTouchOutside(true)
                                .dismissOnBackPressed(true)
                                .asCustom(
                                    LiveCartListAudiencePopupView(this@LiveBroadcastActivity,liveModel!!.anchorId,liveId!!)
                                )
                                .show()
                        }
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_GOODS && rxBusBean.sign == CustSignKey.CUST_LIVE_GOODS -> {
                        //直播商品 显示当前讲解的某个商品
                        var goodBean= rxBusBean.anyBean as CusuLiveGoodsModel
                        loge("获取讲解中的数据="+goodBean.toString())
                        goodBean.let {
                            binding.llGoods.visibility= View.VISIBLE
                            binding.tvTitle.text=it.title
                            binding.tvPrice.text=it.pay_jifen
                            GlideUtil.ImageLoad(this@LiveBroadcastActivity,it.images,binding.img)
                            goodsPid=it.pid
                        }
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_GOODS_REFRESH && rxBusBean.sign == CustSignKey.CUST_LIVE_GOODS_REFRESH -> {
                        //直播商品 上架或者下架刷新v
                        //上架 穿空 下架穿id
                        val bean = rxBusBean.anyBean as CusuLiveGoodsRefreshModel
                        bean.pid?.let {
                            if(it==goodsPid){
                                binding.llGoods.visibility= View.GONE
                            }
                        }
                        binding.LiveCartView.setViewVisibility(true)
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_HEAD && rxBusBean.sign == CustSignKey.CUST_LIVE_HEAD -> {
                        //主播头像
                        //某个用户信息
                        seeInfo(liveModel!!.anchorId!!)

                    }
                    rxBusBean.id == CustSignKey.LIVE_TASK && rxBusBean.sign == CustSignKey.LIVE_TASK -> {
                        //todo  任务 评论 以及分享
                        var index= rxBusBean.anyBean as Int
                        val mapTask: HashMap<String, Any> = HashMap()
                        mapTask["type"] = index
                        GsonUtil.mapToJsonStrObjEncryption(mapTask)?.let { it1 -> mViewModel.onZbFinishTaskMethod(it1) }

                    }
                }
            }

        //房间信息
        val map: HashMap<String, Any> = HashMap()
        map["tuid"] = pageParam!!.liveModel.anchorId
        map["live_id"] = liveId!!
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onRoomInfoMethod(it1) }

        //是否有红包
        val mapRed: java.util.HashMap<String, Any> = java.util.HashMap()
        mapRed.put("live_id",liveId!!)
        loge("live_id="+liveId!!)
        GsonUtil.mapToJsonStrObjEncryption(mapRed)?.let { it1 -> mViewModel.onGetLiveRedMethod(it1) }




        lifecycle.addObserver(binding.llCustGifLayout)
        binding.llCustGifLayout.setGiftAdapter(object : RewardLayout.GiftAdapter<SendGiftBean>{
            override fun onInit(view: View, bean: SendGiftBean): View {
                val ivHeader = view.findViewById<CircleImageView>(R.id.ivHeader)
                val ivGift = view.findViewById<ImageView>(R.id.ivGift)
                val tvNickName = view.findViewById<TextView>(R.id.tvNickName)
                val tvGiftName = view.findViewById<TextView>(R.id.tvGiftName)
                val tvGiftAmount = view.findViewById<TextView>(R.id.tvGiftAmount)
                // 初始化数据
                tvGiftAmount.text = "${bean.theSendGiftSize}"
                bean.theGiftCount = bean.theSendGiftSize
                GlideUtil.ImageLoad(this@LiveBroadcastActivity,bean.userImg,ivHeader)
                GlideUtil.ImageLoad(this@LiveBroadcastActivity,bean.giftImg,ivGift)
                tvNickName.text = bean.userName
                tvGiftName.text = bean.giftName
                return view
            }

            override fun onUpdate(view: View, o: SendGiftBean, t: SendGiftBean): View {
                val ivHeader = view.findViewById<CircleImageView>(R.id.ivHeader)
                val ivGift = view.findViewById<ImageView>(R.id.ivGift)
                val tvNickName = view.findViewById<TextView>(R.id.tvNickName)
                val tvGiftName = view.findViewById<TextView>(R.id.tvGiftName)
                val tvGiftAmount = view.findViewById<TextView>(R.id.tvGiftAmount)
                val showNum = o.theGiftCount + o.theSendGiftSize
                tvGiftAmount.text = "${showNum}"
                GlideUtil.ImageLoad(this@LiveBroadcastActivity,o.userImg,ivHeader)
                GlideUtil.ImageLoad(this@LiveBroadcastActivity,o.giftImg,ivGift)
                // 数字刷新动画
                AnimUtils.start(tvGiftAmount)
                // 更新累计礼物数量
                o.theGiftCount = showNum
                return view
            }

            override fun onKickEnd(bean: SendGiftBean?) {
                loge("收到的礼物onKickEnd:")
            }

            override fun onComboEnd(bean: SendGiftBean?) {
                loge("收到的礼物onComboEnd:")
            }

            override fun addAnim(view: View) {
                val ivHeader = view.findViewById<CircleImageView>(R.id.ivHeader)
                val ivGift = view.findViewById<ImageView>(R.id.ivGift)
                val tvNickName = view.findViewById<TextView>(R.id.tvNickName)
                val tvGiftName = view.findViewById<TextView>(R.id.tvGiftName)
                val tvGiftAmount = view.findViewById<TextView>(R.id.tvGiftAmount)
                // 整个giftView动画
                val giftInAnim = AnimUtils.getInAnimation(this@LiveBroadcastActivity)
                // 礼物图像动画
                val imgInAnim = AnimUtils.getInAnimation(this@LiveBroadcastActivity)
                // 首次连击动画
                imgInAnim?.startTime = 500
                imgInAnim?.setAnimationListener(object : Animation.AnimationListener {
                    override fun onAnimationStart(animation: Animation) {
                        tvGiftAmount.visibility = View.GONE
                    }

                    override fun onAnimationEnd(animation: Animation) {
                        tvGiftAmount.visibility = View.VISIBLE
                        AnimUtils.start(tvGiftAmount)
                    }

                    override fun onAnimationRepeat(animation: Animation) {}
                })
                view!!.startAnimation(giftInAnim)
                ivGift.startAnimation(imgInAnim)
            }

            override fun outAnim(): AnimationSet? {
                return AnimUtils.getOutAnimation(this@LiveBroadcastActivity)
            }

            override fun checkUnique(o: SendGiftBean?, t: SendGiftBean?): Boolean {
                return o!!.theGiftId == t!!.theGiftId && o.theUserId == t.theUserId
            }

            override fun generateBean(bean: SendGiftBean?): SendGiftBean? {
                try {
                    val newBean = bean as SendGiftBean?
                    newBean?.clone()
                    return newBean
                } catch (e: CloneNotSupportedException) {
                    e.printStackTrace()
                }
                return null
            }

        })
        //监听收到礼物消息
        auiMessageService!!.addMessageListener(object : SimpleOnMessageListener() {
            override fun onGiftReceived(message: AUIMessageModel<GiftModel>?) {
                super.onGiftReceived(message)

                loge("收到的礼物:"+message.toString())

                message?.let {
                    val sendGiftBean = SendGiftBean(
                        it.data.userId,
                        it.data.gifGid,
                        1,
                        it.data.userName,
                        it.data.gifTitle,
                        it.data.gifImg,
                        it.data.userPortrait,
                        2000
                    )
                    binding.llCustGifLayout.put(sendGiftBean)
//                    if (mLianMaiAdapter.data.size>1){
//                        for(i in mLianMaiAdapter.data.indices){
//                            if (it.data.gifReceiveId==mLianMaiAdapter.data[i].uid){
//                                mLianMaiAdapter.data[i].price =it.data.gifTotalprice
//                                break
//                            }
//                        }
//                        mLianMaiAdapter.notifyDataSetChanged()
//                    }

                    //这里是收到的礼物
                    if (!TextUtils.isEmpty(it.data.gifSvgUrl)){
//                        Thread {
//                            loopDatas.offer(it.data.gifSvgUrl) //添加数据
//                        }.start()
                        queue.offer(it.data.gifSvgUrl)
                        if (queue.size == 1) {
                            playNextSvga()
                        }

                    }

                }

            }
        })
        binding.rvListHead.layoutManager =  LinearLayoutManager(this, RecyclerView.HORIZONTAL,false)
        binding.rvListHead.adapter = mHeadAdapter
        mHeadAdapter.setNewInstance(mListHead)
        mHeadAdapter.setOnItemClickListener { adapter, view, position ->
            //某个用户信息
            seeInfo(mHeadAdapter.getItem(position).uid)
        }
        isOnClick=false
        getImListData()

        //连麦 list
        getLianMaiListData()

        binding.imgGifSvga.callback = object : SVGACallback {
            override fun onFinished() {
//                   loge("动画结束onFinished")
                // 模拟 SVGA 动画播放完毕后的回调
                executor.submit {
                    // 从队列中移除已经播放完的 SVGA
                    queue.poll()
                    // 继续播放下一个 SVGA
                    playNextSvga()
                }

            }
            override fun onPause() {
//                    loge("onPause")
            }
            override fun onRepeat() {
//                    loge("重复播放onRepeat")
            }
            override fun onStep(frame: Int, percentage: Double) {
//                    loge("动画步骤onStep")
            }
        }
        startLoopBarrageListener()

        //播放svg的队列
//        startLoopListener()
        //获取日常任务、
        mViewModel.onZbTaskListMethod("")

    }
    // 创建单线程的线程池和队列
    val executor = Executors.newSingleThreadExecutor()
    val queue = LinkedBlockingQueue<String>()
    // 播放下一个 SVGA 动画
    fun playNextSvga() {
        if (queue.isEmpty()) {
            return
        }
        val svgaUrl = queue.peek()
        playSvga(svgaUrl)
    }
    // 播放 SVGA 动画
    fun playSvga(svgaUrl: String) {
        // 模拟播放 SVGA 动画
        val  parser = SVGAParser(this@LiveBroadcastActivity)
        parser.decodeFromURL(URL(svgaUrl),object:
            SVGAParser.ParseCompletion{
            override fun onComplete(videoItem: SVGAVideoEntity) {
                var drawable =  SVGADrawable(videoItem)
                binding.imgGifSvga.bringToFront()
                binding.imgGifSvga.setImageDrawable(drawable);
                binding.imgGifSvga.startAnimation()
                loge("礼物svg哈哈哈哈"+svgaUrl)
            }
            override fun onError() {
                loge("礼物svg出错")
            }

        } )

    }


    private val loopBarrageDatas: Queue<String> = ConcurrentLinkedQueue() //队列
    private val loopBarrageThreadExecutor = Executors.newSingleThreadExecutor()
    //收到直播间弹幕消息通知
    fun startLoopBarrageListener() {
        loopBarrageThreadExecutor.execute {
            try {
                while (true) {
                    if (loopBarrageDatas.size > 0) {
                        val value = loopBarrageDatas.poll()
                        if (value != null) {
                            CustRouter.sendLiveBuyGoodsMsg(liveContext!!.groupId,value)
                        }
                        Thread.sleep(500) //队列执行间隔
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun isActivityValid(): Boolean {
        return !isFinishing && !isDestroyed
    }
    private fun joiGroup(liveContext: LiveContext) {
        val request = JoinGroupRequest()
        request.groupId = groupId
        liveContext.messageService.messageService.joinGroup(request, object :
            InteractionCallback<JoinGroupResponse?> {
            override fun onSuccess(data: JoinGroupResponse?) {
                if (isActivityValid()) {
                    onEnterRoomSuccess(liveModel!!)
                }
            }

            override fun onError(interactionError: InteractionError?) {
                if (isActivityValid()) {
                    onEnterRoomError(interactionError!!.msg)
                    // 进入失败时, 退出房间
                    val message = String.format("进入房间失败：\n%s", interactionError!!.msg)
                    DialogUtil.confirm(this@LiveBroadcastActivity, message,
                        { finish() }
                    ) { finish() }
                }
            }
        })
    }

    /**
     * 当系统的配置信息发生改变时，系统会调用此方法。注意，只有在配置文件AndroidManifest中处理了configChanges属性对应的设备配置，该方法才会被调用。
     * 如果发生设备配置与在配置文件中设置的不一致，则Activity会被销毁并使用新的配置重建。
     * 例如：当屏幕方向发生改变时，Activity会被销毁重建，如果在AndroidManifest文件中处理屏幕方向配置信息如下
     */
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        componentManager.dispatchActivityConfigurationChanged(newConfig)
    }
    private fun onEnterRoomSuccess(liveModel: LiveModel) {
        this.liveModel = liveModel
        componentManager.dispatchEnterRoomSuccess(liveModel)
        val req = ImGetGroupStatisticsReq()
        req.groupId = groupId
        interactionService!!.getGroupStatistics(req, object : Callback<ImGetGroupStatisticsRsp?> {
            override fun onSuccess(rsp: ImGetGroupStatisticsRsp?) {
                if (Utils.isActivityValid(this@LiveBroadcastActivity)) {
                    componentManager.post(Actions.GET_GROUP_STATISTICS_SUCCESS, rsp)
                }
            }

            override fun onError(error: Error) {}
        })
    }

    private fun onEnterRoomError(errorMsg: String) {
        componentManager.dispatchEnterRoomError(errorMsg)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        componentManager.dispatchActivityResult(requestCode, resultCode, data)
    }
    override fun onPause() {
        super.onPause()
        componentManager.dispatchActivityPause()
        binding.llCustGifLayout.onPause()
    }

    override fun onResume() {
        super.onResume()
        componentManager.dispatchActivityResume()
        binding.llCustGifLayout.onResume()
    }

    override fun onBackPressed() {
            if (!componentManager.interceptBackKey()) {
                super.onBackPressed()
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        componentManager.dispatchActivityDestroy()
        lifecycle.removeObserver(binding.llCustGifLayout)
        binding.llCustGifLayout.onDestroy()
        InteractionEngine.instance().logout(null)

        if (taskCountDownTimer!=null)
            taskCountDownTimer!!.cancel()
        taskCountDownTimer=null
    }

    override fun finish() {
        super.finish()
        componentManager.dispatchActivityFinish()
    }




    /** 当前观众 list **/
    private fun getImListData(){
        val req = ImListGroupUserReq()
        req.groupId = groupId
        req.sortType = SortType.TIME_ASC.value
        req.pageNum = 1
        req.pageSize = 50
        interactionService!!.listGroupUser(req, object : Callback<ImListGroupUserRsp> {
            override fun onSuccess(rsp: ImListGroupUserRsp) {
                val total = rsp.total
                val userList = rsp.userList
                loge("还有数据="+total+"groupId="+groupId)
                var mListIds: MutableList<String> = ArrayList()
                mListIds.clear()
                if (userList.size>0){
                    for (i in userList.indices)
                        mListIds.add(userList[i].userId)
                    val map: HashMap<String, Any> = HashMap()
                    map["uids"] = StringUtil.convertListToString(mListIds)!!
                    map["vid"] =liveId!!
                    var json= GsonUtil.mapToJsonStrObjEncryption(map)
                    mViewModel.onGetIdsListMethod(json!!)
                }

            }

            override fun onError(error: Error) {}
        })
    }


    /** 连麦 list **/
    private fun getLianMaiListData(){
        // 连麦
        val request = GetMeetingInfoRequest()
        request.id = liveId!!
        AppServerApi.instance().getMeetingInfo(request).invoke(object :
            InteractionCallback<MeetingInfo?> {
            override fun onSuccess(meetingInfo: MeetingInfo?) {
                loge("连麦看看===onSuccess")
            }
            override fun onError(interactionError: InteractionError?) {
                loge("连麦看看===onError")
                showToast(interactionError!!.msg)
            }
        })
    }


    override fun initData() {
        super.initData()
        binding.liveCount.setOnClickListener {
            isOnClick=true
            getImListData()
        }
        binding.hongbao.setSingleClickListener {
            loge("当前红包id ="+packetid)
            val map: java.util.HashMap<String, Any> = java.util.HashMap()
            map["packet_id"] = packetid
            val json=  GsonUtil.mapToJsonStrObjEncryption(map)
            mViewModel.onGetPacketSubmitMethod(json!!)
        }
        binding.tvBtnTheCharts.setSingleClickListener {
            //排行榜
            XPopup.Builder(this@LiveBroadcastActivity)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                .customHostLifecycle(lifecycle)
                .dismissOnTouchOutside(true)
                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                .asCustom(
                    LiveTheChartsBangListPopupView(this@LiveBroadcastActivity, liveId!!,liveModel!!.anchorId!!)
                )
                .show()
        }
        binding.imgBtnClose.setSingleClickListener {
            binding.llGoods.visibility=View.GONE
        }
        binding.llGoods.setSingleClickListener {
            //商品详情
            if(!TextUtils.isEmpty(goodsPid)){
                startKtxActivity<IntegralGoodsDetailActivity>(
                    value =  "pid" to goodsPid
                )
            }
        }
    }

    /** 直播间设置和取消 禁言 通知 **/
    fun isSetUpImMsg(id:String,isUp:Boolean) {
        if (isUp){
            val req = ImMuteUserReq()
            req.groupId = groupId
            req.broadCastType = BroadcastType.SPECIFIC.value
            req.muteUserList =
                object : java.util.ArrayList<String?>() {
                    init {
                        add(id)
                    }
                }
            interactionService!!.muteUser(req,null)
        } else{
            val req = ImCancelMuteUserReq()
            req.groupId = groupId
            req.broadCastType = BroadcastType.SPECIFIC.value
            req.cancelMuteUserList =
                object : java.util.ArrayList<String?>() {
                    init {
                        add(id)
                    }
                }
            interactionService!!.cancelMuteUser(req,null)
        }
    }


    /**
     * 倒计时函数
     */
    inner class MyCountDownTimer(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {
        //计时过程
        override fun onTick(l: Long) {
            //防止计时过程中重复点击
//            binding.tvBtnCode.text = (l / 1000).toString() + "s"
            var time =(l / 1000).toInt()
            var mm:Int=(time%3600) /60
            var ss:Int=(time%3600) %60

            var minute =if(mm<10)"0$mm" else mm
            var second =if(ss<10)"0$ss" else ss
            binding.tvRedTime.text ="$minute:$second"
        }

        //计时完毕的方法
        override fun onFinish() {
            //设置可点击
            binding.tvRedTime.visibility=View.GONE
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@LiveBroadcastActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@LiveBroadcastActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                doStop()
                LoginHelper.startLoginPage()
            }
            onRoomInfoData.observe(this@LiveBroadcastActivity) {
                //房间信息
                isFollow=it.data.data.iffollow==1
                componentManager.post("isFollow", isFollow)
                isShop=it.data.data.ifdianshang
                Log.e("我草看看11111", "run: " + it.data.data.cansay + "xxxx==" + it.data.data.cansaymemo)
                binding.liveInputView.spealStatus(it.data.data.cansay,it.data.data.cansaymemo)
                loge("当前人数倍数==="+it.data.data.number_multiple)
                LiveBlackList.numberMultiple =if(it.data.data.number_multiple>0) it.data.data.number_multiple else 7




                if(it.data.data.cart_product.id>0 && !TextUtils.isEmpty(it.data.data.cart_product.pid)){
                    if (UserManager.getUserId()!=pageParam!!.liveModel.anchorId){
                        //是观众
                        binding.llGoods.visibility= View.VISIBLE
                        binding.tvTitle.text=it.data.data.cart_product.title
                        binding.tvPrice.text=it.data.data.cart_product.pay_jifen
                        GlideUtil.ImageLoad(this@LiveBroadcastActivity,it.data.data.cart_product.images,binding.img)
                        goodsPid=it.data.data.cart_product.pid
                    }
                }




            }

            getRewardErrorData.observe(this@LiveBroadcastActivity) {
                //其他错误
                showToast(it.msg)
                if (it.code == 3){
                    showToast(it.msg)
                    var bundle = Bundle()
                    bundle.putString("packetid",packetid)
                    startActivity(RedExtensionIndexActivity().javaClass,bundle)
                }else{
                    //其他错误
                    showToast(it.msg)
                }
            }
            onUserFollowData.observe(this@LiveBroadcastActivity) {
                //关注。
                isFollow= it.data.data.flag==1
                componentManager.post("isFollow", isFollow)

            }
            onGetLiveRedData.observe(this@LiveBroadcastActivity){
//                查询是否有红包。
                if (it.data!=null){
                    if (it.data.packet_id>0){
                        loge("红包倒计时="+it.data.count_down_seconds)
                        packetid=it.data.packet_id.toString()
                        binding.hongbao.visibility=View.VISIBLE
                        if (it.data.count_down_seconds>0){
                            binding.tvRedTime.visibility=View.VISIBLE
                            myCountDownTimer=null
                            myCountDownTimer = MyCountDownTimer( (1000 *it.data.count_down_seconds).toLong() , 1000)
                            myCountDownTimer?.start()
                        }else{
                            binding.tvRedTime.visibility=View.GONE
                        }
                    }
                }
            }
            onGetPacketSubmitData.observe(this@LiveBroadcastActivity){
                //抢红包
                var listStr :MutableList<String> = mutableListOf()
                listStr.add("$userName 幸运大爆发，成功抢得直播间红包！")
                listStr.add("$userName 实力抢包，红包雨中一鸣惊人！")
                listStr.add("$userName 手气爆棚，成功抢走直播间的红包！")
                listStr.add("恭喜"+userName+"成功揽获直播间红包，让我们一起分享他的喜悦！")
                listStr.add("大家快来围观 $userName 的抢红包绝技，他真是太厉害了！")
                listStr.add("恭喜 $userName ，他的抢红包手气爆棚，让我们一起分享他的喜悦和幸运！")
                val size = random.nextInt(0, listStr.size)
                CustRouter.sendLiveBuyGoodsMsg(liveContext!!.groupId,listStr[size])
                var bundle =Bundle()
                bundle.putString("packetid",packetid)
                startActivity(RedExtensionIndexActivity().javaClass,bundle)
            }
            onGetIdsListData.observe(this@LiveBroadcastActivity) {
                if (it.data.list.isNotEmpty())
                    mHeadAdapter.replaceData(it.data.list)
                if (isOnClick){
                    //当前直播间成员列表
                    XPopup.Builder(this@LiveBroadcastActivity)
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                        .customHostLifecycle(lifecycle)
                        .dismissOnTouchOutside(true)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            LiveAudienceListPopupView(this@LiveBroadcastActivity,
                                it.data.list as MutableList<LiveUserInfoBean>,pageParam!!.role.value,liveId!!,liveModel!!.anchorId
                            )
                        )
                        .show()
                }
            }
            onZbTaskListData.observe(this@LiveBroadcastActivity){
                //获取日常任务
                //任务状态
                if (it.data.isNotEmpty()){
                    binding.llTask.visibility=View.VISIBLE
                    //任务 看直播10分钟
                    val beanLiveTime =it.data.find { it.type=="1" }
                    if (beanLiveTime!=null){
                        if (beanLiveTime.count>=beanLiveTime.target){
                            binding.llTaskLive.visibility=View.GONE
                        }else {
                            binding.llTaskLive.visibility=View.VISIBLE
                            binding.tvTask1.text="0/1  看直播"
                            if (isTaskLiveClick){
                                binding.llTaskLive.setBackgroundResource(R.drawable.ll_bg_anchor_profile)
                                binding.tvTask1.setBackgroundResource(0)
                                binding.tvTaskLiveTime.visibility=View.VISIBLE
                            }else{
                                binding.llTaskLive.setBackgroundResource(0)
                                binding.tvTask1.setBackgroundResource(R.drawable.ilr_bg_anchor_profile)
                                binding.tvTaskLiveTime.visibility=View.GONE
                            }
                            //没有完成任务 打开计时器
                            if (taskCountDownTimer==null)
                                taskTime()
                        }
                    }else binding.llTaskLive.visibility=View.GONE
                    //任务    评论10条
                    val beanLiveComment =it.data.find { it.type=="2" }
                    if (beanLiveComment!=null){
                        isTaskComment=beanLiveComment.count >=beanLiveComment.target
                        if (beanLiveComment.count>=beanLiveComment.target){
                            binding.tvTask2.visibility=View.GONE
                        }else {
                            binding.tvTask2.visibility=View.VISIBLE
                            binding.tvTask2.text=  "${beanLiveComment.count}/${beanLiveComment.target}  评论"
                        }
                    }else binding.tvTask2.visibility=View.GONE
                    //任务 分享3次
                    val beanLiveShare =it.data.find { it.type=="3" }
                    if (beanLiveShare!=null){
                        isTaskShare=beanLiveShare.count >=beanLiveShare.target
                        if (beanLiveShare.count>=beanLiveShare.target){
                            binding.tvTask3.visibility=View.GONE
                        }else {
                            binding.tvTask3.visibility=View.VISIBLE
                            binding.tvTask3.text= "${beanLiveShare.count}/${beanLiveShare.target}  分享"
                        }
                    }else binding.tvTask3.visibility=View.GONE
                }else binding.llTask.visibility=View.GONE

            }
        }
    }

    inner class LiveContextImpl : LiveContext {
        override fun getActivity(): Activity {
            return this@LiveBroadcastActivity
        }
        override fun getRole(): LiveRole {
            return this@LiveBroadcastActivity.role!!
        }

        override fun getNick(): String {
            return this@LiveBroadcastActivity.userNick!!
        }

        override fun getAvatar(): String {
            return this@LiveBroadcastActivity.userAvatar!!
        }

        override fun getTips(): String {
            return this@LiveBroadcastActivity.tips!!
        }

        override fun getLiveStatus(): LiveStatus {
            return this@LiveBroadcastActivity.liveStatus!!
        }

        override fun getEventManager(): EventManager {
            return this@LiveBroadcastActivity.componentManager
        }

        override fun isPushing(): Boolean {
            return this@LiveBroadcastActivity.isPushing
        }

        override fun setPushing(isPushing: Boolean) {
            this@LiveBroadcastActivity.isPushing = isPushing
        }

        override fun isFollow(): Boolean {
            return this@LiveBroadcastActivity.isFollow
        }

        override fun isLandscape(): Boolean {
            return this@LiveBroadcastActivity.resources
                .configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
        }

        override fun setLandscape(landscape: Boolean) {
            if (landscape) {
                // 竖屏 => 横屏
                this@LiveBroadcastActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            } else {
                // 横屏 => 竖屏
                this@LiveBroadcastActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            }
        }

        override fun getLiveId(): String {
            return this@LiveBroadcastActivity.liveId!!
        }

        override fun getGroupId(): String {
            return this@LiveBroadcastActivity.groupId!!
        }

        override fun getUserId(): String {
            return Const.getUserId()
        }

        override fun getLiveService(): LiveService {
            if (this@LiveBroadcastActivity.liveService == null) {
                this@LiveBroadcastActivity.liveService = LiveServiceImpl(this@LiveBroadcastActivity, liveContext)
            }
            return this@LiveBroadcastActivity.liveService!!
        }

        override fun getLivePlayerService(): LivePlayerService {
            if (this@LiveBroadcastActivity.livePlayerService == null) {
                this@LiveBroadcastActivity.livePlayerService = LivePlayerServiceImpl(this@LiveBroadcastActivity)
            }
            return this@LiveBroadcastActivity.livePlayerService!!
        }

        override fun getMessageService(): AUIMessageService {
            if (this@LiveBroadcastActivity.auiMessageService == null) {
                this@LiveBroadcastActivity.auiMessageService = AUIMessageServiceFactory.getMessageService(groupId)
            }
            return this@LiveBroadcastActivity.auiMessageService!!
        }

        override fun getInteractionService(): InteractionService {
            if (this@LiveBroadcastActivity.interactionService == null) {
                this@LiveBroadcastActivity.interactionService = InteractionEngine.instance().interactionService
            }
            return this@LiveBroadcastActivity.interactionService!!
        }
//         fun getInteractionService(): InteractionService {
//            if (this@LiveBroadcastActivity.interactionService == null) {
//                this@LiveBroadcastActivity.interactionService = InteractionEngine.instance().interactionService
//            }
//            return this@LiveBroadcastActivity.interactionService!!
//        }

        override fun getLiveLinkMicPushManager(): LiveLinkMicPushManager {
            return this@LiveBroadcastActivity.pushManager!!
        }

        override fun getLiveModel(): LiveModel {
            return this@LiveBroadcastActivity.liveModel!!
        }

        override fun getAnchorPreviewHolder(): AnchorPreviewHolder {
            return this@LiveBroadcastActivity.anchorPreviewHolder
        }

        override fun isOwner(userId: String): Boolean {
            if (liveModel != null) {
                val anchorId = liveModel.anchorId
                if (!TextUtils.isEmpty(anchorId)) {
                    return TextUtils.equals(anchorId, userId)
                }
            }
            return false
        }

    }


    // 查看自己
    private fun seeInfo(id: String){
        //查看
        XPopup.Builder(this@LiveBroadcastActivity)
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .customHostLifecycle(lifecycle)
            .dismissOnTouchOutside(true)
            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
            .asCustom(
                LiveUserInfoPopupView(this@LiveBroadcastActivity,id,liveId!! , liveModel!!.anchorId)
            )
            .show()
    }


    private fun doStop() {
        if (role== LiveRole.ANCHOR){
            // 媒体
            liveService!!.pusherService.stopLive(null)
            // IMSDK
            liveContext!!.messageService.stopLive(null)
            // AppServer
            val request = StopLiveRequest()
            request.id = liveContext!!.liveId
            request.userId = userId
            AppServerApi.instance().stopLive(request).invoke(null)
            liveService!!.pusherService.destroy()
            val groupRequest = LeaveGroupRequest()
            groupRequest.groupId =groupId
            liveContext!!.messageService.getMessageService().leaveGroup(groupRequest, null)
            finish()
        }else{
            finish()
        }

    }



    // 创建单线程的线程池和队列
    val executorMsg = Executors.newSingleThreadExecutor()
    val queueMsg = LinkedBlockingQueue<CustLiveSendDataBean>()
    // 发送下一个
    fun liveSendMsg() {
//        if (queueMsg.isEmpty()) {
//            return
//        }
//        val bean = queueMsg.peek()
//        //发送自定义消息给其他人
//        sendLiveSendMsg( bean.userId,bean.userNick,bean.content)
        executorMsg.execute {
            try {
                while (true) {
                    if (queueMsg.size > 0) {
                        val bean = queueMsg.poll()
                        if (bean != null) {
                            sendLiveSendMsg( bean.uid,bean.nickname,bean.msg)
                        }
                        Thread.sleep((if (bean.interval>0) bean.interval else 120).toLong()) //队列执行间隔
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    //直播间 通知别人 虚拟发送消息
    fun sendLiveSendMsg( uid:String,nickname:String, content :String ){
        // 1. 向组内全员发消息
        val req = ImSendMessageToGroupReq()
        req.groupId =liveContext!!.groupId
        // 指定消息类型
        req.type =300011
        // 指定是否跳过安全审核
        req.skipAudit = true
        // 指定是否跳过禁言处理
        req.skipMuteCheck = true
        // 指定发送数据
        req.data = GsonUtils.getGson().toJson(object : HashMap<String?, Any?>() {
            init {
                put("uid", uid)
                put("nickname", nickname)
                put("msg", content)
            }
        })
        var interactionService = InteractionEngine.instance().interactionService
        interactionService.sendMessageToGroup(req,object :
            Callback<ImSendMessageToGroupRsp> {
            override fun onSuccess(p0: ImSendMessageToGroupRsp?) {
            }
            override fun onError(p0: Error?) {
            }

        })
    }
    var isTaskLiveClick=false
    var taskCountDownTimer: TaskCountDownTimer? = null
    private  fun  taskTime(){
        val timeLong =600  //10分钟 600秒倒计时
        var bean = UserManager.getLiveTask()
        if (bean!=null){
            if(bean.timeDate == TimeUtils.getNowDate()){
                //如果不等于今儿的日期
                val time =UserManager.getLiveTaskTime()
                loge("请求完成当日任务时间继续"+time)
                if(time>=timeLong){
                    loge("请求完成当日任务时间继续"+time+"===="+timeLong)
                    //任务完成 看直播10分钟
                    //todo 统计任务
                    val mapTask: HashMap<String, Any> = HashMap()
                    mapTask["type"] = 1
                    GsonUtil.mapToJsonStrObjEncryption(mapTask)?.let { it1 -> mViewModel.onZbFinishTaskMethod(it1) }
                }else{
                    //开启计时器
                    if (taskCountDownTimer==null)
                        taskCountDownTimer = TaskCountDownTimer(( (timeLong*1000) -(time*1000)).toLong(), 1000)
                    taskCountDownTimer!!.start()
                }
            }else{
                UserManager.setLiveTask(AppLiveTaskData(timeDate =  TimeUtils.getNowDate().toString(), sendNum = bean.sendNum))
                UserManager.setLiveTaskTime(0)
                //开启计时器
                if (taskCountDownTimer==null)
                    taskCountDownTimer = TaskCountDownTimer(((timeLong*1000).toLong()), 1000)
                taskCountDownTimer!!.start()
            }
        }else{
            //为空就是当天。新的
            UserManager.setLiveTask(AppLiveTaskData(timeDate =  TimeUtils.getNowDate().toString(), sendNum = 0))
            UserManager.setLiveTaskTime(0)
            //开启计时器
            if (taskCountDownTimer==null)
                taskCountDownTimer = TaskCountDownTimer(((timeLong*1000).toLong()), 1000)
            taskCountDownTimer!!.start()

        }
    }

    /**
     * 倒计时函数
     */
    inner class TaskCountDownTimer(millisInFuture: Long, countDownInterval: Long) :
        CountDownTimer(millisInFuture, countDownInterval) {
        //计时过程
        override fun onTick(l: Long) {
            //防止计时过程中重复点击
            val minutes = (l / 1000) / 60
            val remainingSeconds = (l / 1000) % 60
            binding.tvTaskLiveTime.text="剩余${minutes}分${remainingSeconds}秒"
            val time =UserManager.getLiveTaskTime()
            UserManager.setLiveTaskTime((time+1))
        }

        //计时完毕的方法
        override fun onFinish() {
            val time =UserManager.getLiveTaskTime()
            loge("请求完成当日任务时间继续"+time)
            val timeLong =600  //10分钟 600秒倒计时
            if(time>=timeLong){
                loge("请求完成当日任务时间继续"+time+"===="+timeLong)
                //任务完成 看直播10分钟
                //todo 统计任务
                val mapTask: HashMap<String, Any> = HashMap()
                mapTask["type"] = 1
                GsonUtil.mapToJsonStrObjEncryption(mapTask)?.let { it1 -> mViewModel.onZbFinishTaskMethod(it1) }
            }
        }
    }
}